/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package clusterAnalysis;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import jsc.contingencytables.ChiSquaredTest;
import jsc.contingencytables.ContingencyTable;
import jsc.onesample.Ttest;
import org.uncommons.maths.random.MersenneTwisterRNG;
import units.CellType;
import units.MonkeyType;
import utils.FileUtils;

/**
 *
 * @author jamie
 */
public class ClusterSourceStats {

    private TreeMap<Integer, List> monkeyTypeMap;
    private TreeMap<Integer, List> sourceMap;
    private TreeMap<Integer, List> cellTypeMap;
    boolean calculatePValues = true;
    boolean isgs_only = true;

    private File outputFolder = new File("/Users/jamie/Dropbox/monkeys/outputForR/clust/pies/");

    public ClusterSourceStats(TreeMap<Integer, List> monkeyTypeMap, TreeMap<Integer, List> sourceMap, TreeMap<Integer, List> cellTypeMap, boolean isgsOnly) {
        this.isgs_only = isgsOnly;
        if(isgsOnly){
            outputFolder = new File("/Users/jamie/Dropbox/monkeys/outputForR/clust/pies_isgsOnly/");
        } else {
            outputFolder = new File("/Users/jamie/Dropbox/monkeys/outputForR/clust/pies/");
        }
        try {
            this.monkeyTypeMap = monkeyTypeMap;
            this.sourceMap = sourceMap;
            this.cellTypeMap = cellTypeMap;
            Object[] rowValues_monkey = {MonkeyType.A, MonkeyType.M};

            testForAssociation(monkeyTypeMap, rowValues_monkey, "monkeyType");
            Object[] rowValues_cellType = {CellType.L, CellType.P};
            testForAssociation(cellTypeMap, rowValues_cellType, "cellType");
            Object[] rowValues_source = {"MP", "ML", "AP", "AL"};
            testForAssociation(sourceMap, rowValues_source, "source");
        } catch (IOException ex) {
            Logger.getLogger(ClusterSourceStats.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void testForAssociation(TreeMap<Integer, List> map, Object[] colValues, String description) throws IOException {
        System.out.println("running for "+description);
        int[][] data = new int[map.keySet().size()][colValues.length];

        for(int clusterId : map.keySet()){
            for(int j=0;j<colValues.length;j++){
                data[clusterId-1][j] = getNoOfOccurrences(colValues[j], map.get(clusterId));
            }
        }
        if(calculatePValues){
            System.out.println("calculating chi-square for "+data.length+"x"+data[0].length);
            ContingencyTable contingencyTable = new ContingencyTable(data);
            ChiSquaredTest chiSquaredTest = new ChiSquaredTest(contingencyTable);
            System.out.println(description+":  "+ chiSquaredTest.getSP()+", "+chiSquaredTest.getTestStatistic()+", "+chiSquaredTest.getDegreesOfFreedom());
        }
        BufferedWriter writer = FileUtils.getBufferedWriter(new File(outputFolder, description+".txt"));
        BufferedWriter writer2 = FileUtils.getBufferedWriter(new File(outputFolder, description+"_sum.txt"));
        StringBuffer buffer = new StringBuffer();
        StringBuffer buffer2 = new StringBuffer();

        for(int j=0;j<data[0].length;j++){
            buffer.append(colValues[j]+"\t");
            buffer2.append(colValues[j]+"\t");
        }
        writer.append("clusterSize\t"+buffer.toString().trim()+"\n");
        writer2.append("clusterSize\t"+buffer.toString().trim()+"\n");
        int[] totals = getTotals(colValues, map);

        for(int i=0;i<data.length;i++){
            buffer = new StringBuffer();
            buffer2 = new StringBuffer();
            buffer.append("cluster_"+(i+1)+"\t"+map.get(i+1).size()+"\t");
            buffer2.append("cluster_"+(i+1)+"\t"+map.get(i+1).size()+"\t");
            for(int j=0;j<colValues.length;j++){
                double proportion = (data[i][j]+0.0)/totals[j];
                buffer.append(proportion+"\t");
                int sum = data[i][j];
                buffer2.append(sum+"\t");
            }
            writer.append(buffer.toString().trim()+"\n");
            writer2.append(buffer2.toString().trim()+"\n");
        }
        writer.close();
        writer2.close();
    }

    private int getNoOfOccurrences(Object object, List list) {
        int c=0;
        for(Object o : list){
            if(o.equals(object)){
                c++;
            }
        }
        return c;
    }

    private int[] getTotals(Object[] colValues, TreeMap<Integer, List> map) {
        int[] totals = new int[colValues.length];
        int i=0;
        for(Object colValue : colValues){
            List allList = new ArrayList();
            for(List list : map.values()){
                allList.addAll(list);
            }
            totals[i] = getNoOfOccurrences(colValue, allList);
            System.out.println(totals[i]);
            i++;
        }
        return totals;

    }



    

    

    

    
}
